package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.OrderTechService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @Author liub
 * @Date 2019/12/17 10:31
 * @Version 1.0
 */

@Service
public class OrderTechServiceImpl implements OrderTechService {

    /**
     * 声明日志的静态变量
     */
    private static final Logger logger = LoggerFactory.getLogger(OrderTechServiceImpl.class);

    @Resource
    private OrderTechMapper orderTechMapper;

    @Resource
    private OrderFlowMapper orderFlowMapper;

    @Resource
    private OrderRepairMapper orderRepairMapper;


    /**
     * 查询
     */
    @Override
    public JSONObject queryOrderTech(OrderTech orderTech) {
        try {
            //获取页面的数据个数
            Integer pagesize = orderTech.getPagesize();
            //获取查询的页数
            Integer pageindex = orderTech.getPageindex();
            if (pagesize != null && pageindex != null) {
                orderTech.setIncept(pagesize * (pageindex - 1));
            }
            orderTech.setSourceTypeId(1);
            //执行查询操作
            List<OrderTech> orderTechList =new ArrayList<>();
            if(orderTech.getOrderId()==null){
                return JSONObject.oK(HintMessage.QUERY_NULL, orderTechList, 0);
            }
             orderTechList = orderTechMapper.queryOrderTech(orderTech);

            //如果页数和页面数量都不为空的情况下进行计数
            if (orderTechList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, orderTechList, 0);
            } else {
                Integer count = orderTechMapper.countOrderTech(orderTech);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, orderTechList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }
    }

    /**
     * 新增
     */
    @Override
    public JSONObject insertOrderTech(OrderTech orderTech) {
        try {
            if (orderTech.getOrderTechId() != null) {
                throw new ModifyFailedException(HintMessage.INSERT_ID);
            }
            //初始化基础数据
            if (orderTech.getDataState() == null) {
                orderTech.setDataState(1);
            }
            //判重
            checkParam(orderTech);
            //执行新增操作
            Integer row = orderTechMapper.insertOrderTech(orderTech);
            if (row == 0) {
                throw new ModifyFailedException(HintMessage.INSERT_DEFEATED);
            }
            return JSONObject.oK(HintMessage.INSERT_SUCCESS);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }

    }

    /**
     * 修改
     */
    @Override
    public JSONObject updateOrderTech(OrderTech orderTech) {
        try {
            if (orderTech.getOrderTechId() == null) {
                throw new ParamsErrorException(HintMessage.UPDATE_ID);
            }
            //初始化基础数据
            if (orderTech.getDataState() == null) {
                orderTech.setDataState(1);
            }
            //判重
            checkParam(orderTech);
            //执行修改操作
            int row = orderTechMapper.updateOrderTech(orderTech);
            if (row == 0) {
                throw new ModifyFailedException(HintMessage.UPDATE_DEFEATED);
            }
            return JSONObject.oK(HintMessage.UPDATE_SUCCESS);
        } catch (GlobalException e) {//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 删除
     */
    @Override
    public JSONObject deleteOrderTech(List<Integer> orderTechIds, Integer dataState) {
        try {
            //空值判断
            if (dataState == null) {
                throw new ParamsErrorException(HintMessage.DATASTATE_NULL);
            }
            if (orderTechIds == null) {
                throw new ParamsErrorException(HintMessage.LIST_NULL);
            }
            //记录异常信息
            String msg = "";
            switch (dataState) {
                case 1:
                    msg = HintMessage.START_VALUE;
                    break;
                case 2:
                    msg = HintMessage.DELETE_VALUE;
                    break;
                case 3:
                    msg = HintMessage.STOP_VALUE;
                    break;
                default:
                    throw new ParamsErrorException(HintMessage.VIOLATION_OPERATION);
            }
            //执行删除操作
            int row = orderTechMapper.deleteOrderTech(orderTechIds, dataState);
            //声明msg字符串，用来存抛出的异常
            if (row == 0) {
                msg = msg + HintMessage.DEFEATED_VALUE;
            } else {
                msg = msg + HintMessage.SUCCESS_VALUE;
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 判重
     */
    public void checkParam(OrderTech orderTech) {

        //任务单ID
        Integer orderId = orderTech.getOrderId();
        //创建人ID
        Integer userId = orderTech.getUserId();
        //版本来源ID
        Integer sourceTypeId = orderTech.getSourceTypeId();

        //任务单ID
        if (orderId == null) {
            throw new ParamsErrorException(HintMessage.ORDERID_NULL);
        }
        //创建人ID
        if (userId == null) {
            throw new ParamsErrorException(HintMessage.USERID_NULL);
        }
        //版本来源ID
        if (sourceTypeId == null) {
            throw new ParamsErrorException(HintMessage.SOURCETYPEID_NULL);
        }

    }

    /**
     * 保存工序流程
     */
    @Override
    public JSONObject saveOrderFlow(OrderTech orderTech) {
        try {
            //判空
            if (orderTech == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (orderTech.getOrderTechId() == null) {
                throw new ParamsErrorException(HintMessage.ORDERTECHID_NULL);
            }
            if (orderTech.getOrderId() == null) {
                throw new ParamsErrorException(HintMessage.ORDERID_NULL);
            }


            //获取流程id
            Integer orderTechId = orderTech.getOrderTechId();
            Integer orderId = orderTech.getOrderId();
            //获取list集合
            List<OrderFlow> orderFlowList = new ArrayList<>();
            orderFlowList = orderTech.getOrderFlowList();
            for (OrderFlow orderFlow : orderFlowList) {
                orderFlow.setOrderTechId(orderTechId);
                orderFlow.setOrderId(orderId);
            }


            //获取数据库数据
            OrderFlow orderFlow1 = new OrderFlow();
            orderFlow1.setOrderTechId(orderTechId);
            orderFlow1.setOrderId(orderId);
            List<OrderFlow> oldorderFlowList = orderFlowMapper.queryOrderFlow(orderFlow1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldorderFlowList != null) {
                for (OrderFlow orderFlow : oldorderFlowList
                ) {
                    oldIds.add(orderFlow.getOrderFlowId());
                }
            }
            if (orderFlowList != null) {
                for (OrderFlow orderFlow : orderFlowList
                ) {
                    newIds.add(orderFlow.getOrderFlowId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = orderFlowMapper.deleteOrderFlow(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (orderFlowList != null) {
                for (OrderFlow orderFlow : orderFlowList
                ) {
                    if (orderFlow.getDataState() == null) {
                        orderFlow.setDataState(1);
                    }

                    if (orderFlow.getOrderFlowId() != null) {
                        if (orderFlow.getOrderFlowId().equals(0)) {
                            orderFlow.setOrderFlowId(null);
                            // 执行判重操作
                            Integer Counts = orderFlowMapper.checkOrderFlow(orderFlow);
                            if (Counts == 0) {
                                insertrow = insertrow + orderFlowMapper.insertOrderFlow(orderFlow);
                            }

                        } else {
                            // 执行判重操作
                            Integer Counts = orderFlowMapper.checkOrderFlow(orderFlow);
                            if (Counts == 0) {
                                updaterow = updaterow + orderFlowMapper.updateOrderFlow(orderFlow);
                            }
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }


    /**
     * 保存维修流程
     */
    @Override
    public JSONObject saveOrderRepair(OrderTech orderTech) {
        try {
            //判空
            if (orderTech == null) {
                throw new ParamsErrorException(HintMessage.DATA_NULL);
            }
            if (orderTech.getOrderTechId() == null) {
                throw new ParamsErrorException(HintMessage.ORDERTECHID_NULL);
            }
            if (orderTech.getOrderId() == null) {
                throw new ParamsErrorException(HintMessage.ORDERID_NULL);
            }

            //获取流程id
            Integer orderTechId = orderTech.getOrderTechId();
            Integer orderId = orderTech.getOrderId();
            //获取list集合
            List<OrderRepair> OrderRepairList = new ArrayList<>();
            OrderRepairList = orderTech.getOrderRepairList();
            for (OrderRepair orderRepair : OrderRepairList) {
                orderRepair.setOrderTechId(orderTechId);
                orderRepair.setOrderId(orderId);
            }


            //获取数据库数据
            OrderRepair orderRepair1 = new OrderRepair();
            orderRepair1.setOrderTechId(orderTechId);
            orderRepair1.setOrderId(orderId);
            List<OrderRepair> oldOrderRepairList = orderRepairMapper.queryOrderRepair(orderRepair1);
            //删除
            List<Integer> deleteList = new ArrayList<>();
            List<Integer> oldIds = new ArrayList<>();
            List<Integer> newIds = new ArrayList<>();
            if (oldOrderRepairList != null) {
                for (OrderRepair orderRepair : oldOrderRepairList
                ) {
                    oldIds.add(orderRepair.getOrderRepairId());
                }
            }
            if (OrderRepairList != null) {
                for (OrderRepair orderRepair : OrderRepairList
                ) {
                    newIds.add(orderRepair.getOrderRepairId());
                }
            }
            HashSet h1 = new HashSet(oldIds);
            HashSet h2 = new HashSet(newIds);
            h1.removeAll(h2);
            deleteList.addAll(h1);
            int deleterow = 0;
            int insertrow = 0;
            int updaterow = 0;
            if (deleteList.size() != 0) {
                deleterow = orderRepairMapper.deleteOrderRepair(deleteList, 2);
            }
            //删除完成  进行新增 和 修改
            if (OrderRepairList != null) {
                for (OrderRepair orderRepair : OrderRepairList
                ) {
                    if (orderRepair.getDataState() == null) {
                        orderRepair.setDataState(1);
                    }


                    if (orderRepair.getOrderRepairId() != null) {
                        if (orderRepair.getOrderRepairId().equals(0)) {
                            orderRepair.setOrderRepairId(null);
                            // 执行判重操作
                            Integer Counts = orderRepairMapper.checkOrderRepair(orderRepair);
                            if (Counts == 0) {
                                insertrow = insertrow + orderRepairMapper.insertOrderRepair(orderRepair);
                            }

                        } else {
                            // 执行判重操作
                            Integer Counts = orderRepairMapper.checkOrderRepair(orderRepair);
                            if (Counts == 0) {
                                updaterow = updaterow + orderRepairMapper.updateOrderRepair(orderRepair);
                            }
                        }
                    }
                }
            }
            return JSONObject.oK(HintMessage.SAVE_SUCCESS, deleterow + insertrow + updaterow);
        } catch (GlobalException e) {// 捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
}
